var WebSocket = require('websocket').server
var http = require('http')

var httpServer = http.createServer().listen(8080, function () {
  console.log('http://127.0.0.1:8080')
})

var wsServer = new WebSocket({
  httpServer: httpServer,
  autoAcceptConnections:false
})

var conArr = []

wsServer.on('request', function (request) {
  var connection = request.accept()
  conArr.push(connection)
  connection.on('message', function (msg) {
    console.log('----msg----', msg)
    // connection.send(msg.utf8Data)
    for (let i = 0; i < conArr.length; i++ ) {
      conArr[i].send(msg.utf8Data)
    }
  })
})



// const express = require('express');
// const http = require('http');
// const WebSocket = require('ws');

// const app = express();
// const server = http.createServer(app);
// const wss = new WebSocket.Server({ server });

// wss.on('connection', function connection(ws) {
//     console.log('Client connected.');

//     // Send welcome message to the client
//     ws.send('Welcome to the chat server!');

//     // Listen for messages from the client
//     ws.on('message', function incoming(message) {
//         console.log(`received: ${message}`);

//         // Broadcast received message to all clients
//         wss.clients.forEach(function each(client) {
//             if (client !== ws && client.readyState === WebSocket.OPEN) {
//                 client.send(message);
//             }
//         });
//     });

//     // Handle disconnections
//     ws.on('close', function close() {
//         console.log('Client disconnected.');
//     });
// });

// // Start the server on port 3000
// server.listen(3000, function listening() {
//     console.log('Listening on %d', server.address().port);
// });